<?php

/**
 * 特批授权仓库
 * @author yuzy 2015-5-13
 */

namespace common\repositories\myhtsq;

use common\repositories\BaseRepository;
use common\support\StringHelper;
use common\support\Helper;
use common\entities\myhtsq\SpecialApprovalAuthorizeEntity;
use common\error\ErrorCode;
use Exception;

class SpecialApprovalAuthorizeRepository extends BaseRepository
{

    /**
     * 构造方法
     * @param unknown $config (optional)
     */
    public function __construct($config = [])
    {
        parent::__construct($config);
    }

    /**
     * 特批授权列表
     * @param \common\support\PageParam $pageParam 分页参数
     * @param integer $areaId 区域id
     * @param string $fulfil
     * @param string $keyword 关键字
     * @return array
     */
    public static function getSpecialApprovalAuthorizeList($pageParam, $areaId, $fulfil, $keyword)
    {
        $skip = $pageParam->getSkipByPageParam();
        $query = SpecialApprovalAuthorizeEntity::find();
        $query->select("myscrm_special_approval_authorize.*,principal.UserName as principal_name,"
            . "myscrm_organization.UniqueName,myscrm_organization.FriendlyName,"
            . "myscrm_contract_manage.customer_name,myscrm_contract_manage.contract_id,businessunit.BUName as area_name,myscrm_contract_manage.erp_contract_code,myscrm_contract_business_type.business_type_name");
        //区域id
        if (!empty($areaId)) {
            $query->andWhere(['myscrm_special_approval_authorize.promise_fulfil_areaid' => $areaId]);
        }

        // 是否兑现
        if ($fulfil <> '') {
            if ($fulfil == '1') {
                $query->andWhere('myscrm_special_approval_authorize.actual_fulfil_time is not null');
            } else {
                $query->andWhere('myscrm_special_approval_authorize.actual_fulfil_time is null');
            }
        }

        // 关键字过滤
        if (!empty($keyword)) {
            $query->andWhere(['or', ['like', 'myscrm_contract_manage.contract_code', $keyword], ['like', 'myscrm_special_approval_authorize.organization_name', $keyword], ['like', 'myscrm_organization.UniqueName', $keyword], ['like', 'myscrm_organization.FriendlyName', $keyword]]);
        }

        $query->leftJoin('myscrm_organization', 'myscrm_organization.Id = myscrm_special_approval_authorize.organization_id')
            ->leftJoin('myscrm_contract_manage', 'myscrm_special_approval_authorize.contract_code = myscrm_contract_manage.contract_code AND IFNULL(myscrm_contract_manage.contract_code,\'\')!=\'\'')
            ->leftJoin('myscrm_erp_user principal', 'principal.userguid = myscrm_special_approval_authorize.promise_fulfil_principle')
            ->leftJoin('myscrm_erp_business_unit businessunit', 'businessunit.BUGUID = principal.BUGUID')
            ->leftJoin('myscrm_contract_business_type','myscrm_contract_business_type.business_type_id = myscrm_contract_manage.business_type_id')
            ->offset($skip)
            ->limit($pageParam->pageSize)
            ->orderBy([$pageParam->sortBy => $pageParam->sortAsc]);

        $result = $query->asArray()->all(); //这里必须asArray，否则无法获取关联字段的属性值

        $totalResult = SpecialApprovalAuthorizeEntity::find();
        if (!empty($areaId)) {
            $totalResult->andWhere(['myscrm_special_approval_authorize.promise_fulfil_areaid' => $areaId]);
        }
        if ($fulfil <> '') {
            if ($fulfil == '1') {
                $totalResult->andWhere('myscrm_special_approval_authorize.actual_fulfil_time is not null');
            } else {
                $totalResult->andWhere('myscrm_special_approval_authorize.actual_fulfil_time is null');
            }
        }
        if (!empty($keyword)) {
            $totalResult->andWhere(['or', ['like', 'myscrm_contract_manage.contract_code', $keyword], ['like', 'myscrm_organization.UniqueName', $keyword], ['like', 'myscrm_organization.FriendlyName', $keyword]]);
        }
        $totalResult->leftJoin('myscrm_organization', 'myscrm_organization.Id = myscrm_special_approval_authorize.organization_id')
            ->leftJoin('myscrm_contract_manage', 'myscrm_special_approval_authorize.contract_code = myscrm_contract_manage.contract_code AND IFNULL(myscrm_contract_manage.contract_code,\'\')!=\'\'');
        $total = $totalResult->count();

        $pageResult = Helper::setPageResult($total, $result);
        return $pageResult;
    }

    /**
     * 获取特批授权实体信息
     * @param string $authorizeId
     * @return \common\entities\myhtsq\SpecialApprovalAuthorizeEntity
     */
    public static function getSpecialApprovalAuthorizeInfo($authorizeId)
    {
        return SpecialApprovalAuthorizeEntity::find()
            ->select('myscrm_special_approval_authorize.*,principal.username as principal_name,myscrm_organization.UniqueName,myscrm_organization.FriendlyName,myscrm_contract_manage.erp_contract_code')
            ->where(['special_approval_authorize_id' => $authorizeId])
            ->leftJoin('myscrm_organization', 'myscrm_organization.Id = myscrm_special_approval_authorize.organization_id')
            ->leftJoin('myscrm_erp_user principal', 'principal.userguid = myscrm_special_approval_authorize.promise_fulfil_principle')
            ->leftJoin('myscrm_contract_manage', 'myscrm_special_approval_authorize.contract_code = myscrm_contract_manage.contract_code AND IFNULL(myscrm_contract_manage.contract_code,\'\')!=\'\'')
            ->asArray()
            ->one();
    }

    /**
     * 新增特批授权
     * @param \common\models\myhtsq\SpecialApprovalAuthorizeModel $authorizeModel
     * @return boolean|string 失败返回false，成功返回新增的特批授权Id
     */
    public function addSpecialApprovalAuthorize($authorizeModel)
    {
        try {
            $entity = new SpecialApprovalAuthorizeEntity();
            $entity->setAttributes($authorizeModel->attributes);
            $entity->special_approval_authorize_id = StringHelper::uuid();
            $result = $entity->save();
            if ($result === FALSE) {
//                $error = $entity->firstErrorMessage;
                return $this->setAndReturn(ErrorCode::ERR_SPECIAL_APPROVAL_AUTHORIZE_SAVE_FAIL);
            } else {
                return $entity->primaryKey;
            }
        } catch (Exception $ex) {
            return $this->setAndReturn(ErrorCode::ERR_SPECIAL_APPROVAL_AUTHORIZE_SAVE_FAIL, (string)$ex);
        }
    }

    /**
     * 更新特批授权
     * @param \common\models\myhtsq\SpecialApprovalAuthorizeModel $authorizeModel
     * @return boolean|string 失败返回false，成功返回编辑的特批授权Id
     */
    public function updateSpecialApprovalAuthorize($authorizeModel)
    {
        try {
            $entity = SpecialApprovalAuthorizeRepository::getSpecialApprovalAuthorizeById($authorizeModel->special_approval_authorize_id);
            if (is_null($entity)) {
                return $this->setAndReturn(ErrorCode::ERR_SPECIAL_APPROVAL_AUTHORIZE_SAVE_FAIL);
            }
            $entity->setAttributes($authorizeModel->toArray());
            $result = $entity->update();
            if ($result === FALSE) {
//                $error = $entity->firstErrorMessage;
                return $this->setAndReturn(ErrorCode::ERR_SPECIAL_APPROVAL_AUTHORIZE_SAVE_FAIL);
            } else {
                return $entity->special_approval_authorize_id;
            }
        } catch (Exception $ex) {
            return $this->setAndReturn(ErrorCode::ERR_SPECIAL_APPROVAL_INVOICE_SAVE_FAIL, (string)$ex);
        }
    }

    /**
     * 根据Id获取特批授权
     * @param type $authorizeId
     * @return \common\entities\myhtsq\SpecialApprovalAuthorizeEntity
     */
    public static function getSpecialApprovalAuthorizeById($authorizeId)
    {
        return SpecialApprovalAuthorizeEntity::findOne(['special_approval_authorize_id' => $authorizeId]);
    }

    /**
     * 根据合同编号，获取特批授权对象
     * @param string $contractCode 合同编号
     * @return \common\entities\myhtsq\SpecialApprovalAuthorizeEntity
     */
    public static function getSpecialApprovalAuthorizeByContractCode($contractCode)
    {
        return SpecialApprovalAuthorizeEntity::find()->where(['contract_code' => $contractCode])->one();
    }

}
